package com.itheima.mysql.impl;

import cn.hutool.core.collection.CollUtil;



import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;

import com.itheima.commons.pojo.Question;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.itheima.commons.pojo.User;
import com.itheima.commons.pojo.UserInfo;
import com.itheima.commons.vo.LinearVo;
import com.itheima.interfaces.UserInfoApi;
import com.itheima.mysql.mapper.UserInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

@Service
public class UserInfoMapperImpl implements UserInfoApi {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Override
    public void insertUserInfo(UserInfo userInfo) {
        userInfoMapper.insert(userInfo);
    }

    @Override
    public void updateUserInfoByLogo(Long uid, String logo) {
        userInfoMapper.update(UserInfo.builder().logo(logo).build(), Wrappers
                .lambdaQuery(UserInfo.class)
                .eq(UserInfo::getUserId, uid)
        );
    }

    @Override
    public UserInfo findUserInfoByUserId(Long uid) {
        UserInfo userInfos = userInfoMapper.selectOne(Wrappers.lambdaQuery(UserInfo.class).eq(UserInfo::getUserId, uid));
        return userInfos;
    }


    @Override
    public Map<Long, UserInfo> findUserInfoListByUserIdsByCondition(UserInfo userInfo, List<Long> userIds, Collection<String> strings) {
        // 查询条件  没有传递过来
        List<UserInfo> userInfos = new ArrayList<>();
        if (ObjectUtil.isEmpty(userInfo)) {
            userInfos = userInfoMapper.selectList(Wrappers.lambdaQuery(UserInfo.class)
                    .in(UserInfo::getUserId, userIds)
                    .notIn(UserInfo::getUserId, strings));
        } else {
            userInfos = userInfoMapper.selectList(Wrappers.lambdaQuery(UserInfo.class)
                            .in(UserInfo::getUserId, userIds)
                            .eq(ObjectUtil.isNotNull(userInfo.getSex()), UserInfo::getSex, userInfo.getSex())
//                    .eq(ObjectUtil.isNotNull(userInfo.getCity()), UserInfo::getCity, userInfo.getCity())
//                    .le(ObjectUtil.isNotNull(userInfo.getAge()), UserInfo::getAge, userInfo.getAge())
                            .like(ObjectUtil.isNotNull(userInfo.getNickName()), UserInfo::getNickName, userInfo.getNickName())
            );
        }

        // 性别的第一个问题  man woman  1 2 在Service层进行转换
        // 如果是个空  APP没有传递
        // Map  "gender":"man"
        // map.get("gender")  ==  man
        // userInfo.getSex 1 , 2
        Map<Long, UserInfo> infoMap = CollUtil.fieldValueMap(userInfos, "userId");
        return infoMap;

    }

    @Override
    public Map<Long, UserInfo> findUserListByUserIds(UserInfo userInfo, List<Long> userIds) {
        // 查询条件  没有传递过来
        List<UserInfo> userInfos = userInfoMapper.selectList(Wrappers.lambdaQuery(UserInfo.class)
                .in(UserInfo::getUserId, userIds));

        Map<Long, UserInfo> infoMap = CollUtil.fieldValueMap(userInfos, "userId");
        return infoMap;

    }

    @Override
    public Map<Long, UserInfo> findUserInfoListByUserIdsBykeyword(List<Long> userId, String keyword) {
        List<UserInfo> userInfos = new ArrayList<>();
        if (StrUtil.isNotEmpty(keyword)) {
            userInfos = userInfoMapper.selectList(Wrappers.lambdaQuery(UserInfo.class)
                    .in(UserInfo::getUserId, userId).like(UserInfo::getNickName, keyword)
            );
        } else {
            userInfos = userInfoMapper.selectList(Wrappers.lambdaQuery(UserInfo.class)
                    .in(UserInfo::getUserId, userId)
            );
        }
        Map<Long, UserInfo> map = CollUtil.fieldValueMap(userInfos, "userId");
        return map;
    }

    @Override
    public Map<Long, UserInfo> findPublishInfo(List<Long> userId) {
        List<UserInfo> userInfos = userInfoMapper.selectList(Wrappers.lambdaQuery(UserInfo.class)
                .in(UserInfo::getUserId, userId));
        Map<Long, UserInfo> map = CollUtil.fieldValueMap(userInfos, "userId");

        return map;
    }

    @Override
    public Map<Long, UserInfo> findUserListByUserIdsByGender(UserInfo userInfo, List<Long> userIds, String gender) {
        // 查询条件  没有传递过来
        List<UserInfo> userInfos = userInfoMapper.selectList(Wrappers.lambdaQuery(UserInfo.class)
                .in(UserInfo::getUserId, userIds).eq(StrUtil.isNotEmpty(gender), UserInfo::getSex, gender.equals("man") ? 1 : 2));

        Map<Long, UserInfo> infoMap = CollUtil.fieldValueMap(userInfos, "userId");
        return infoMap;

    }

    @Override
    public void updateByUserInfo(Long userId, UserInfo userInfo) {
        userInfoMapper.update(userInfo, Wrappers.lambdaQuery(UserInfo.class).eq(UserInfo::getUserId, userId));
    }

    @Override
    public void updateHeader(Long id, String originalFilename) {
        userInfoMapper.update(UserInfo.builder().logo(originalFilename).build(), Wrappers.lambdaQuery(UserInfo.class).eq(UserInfo::getUserId, id));
    }


    @Override
    public List<String> selectIndustry() {
        List<UserInfo> userInfoList = userInfoMapper.selectList(new QueryWrapper<UserInfo>()
                .select("DISTINCT industry").isNotNull("industry"));
        return CollUtil.getFieldValues(userInfoList, "industry", String.class);
    }


    @Override
    public Integer selectIndustryCount(String industry, String startTime, String endTime) {
        Integer count = userInfoMapper.selectCount(Wrappers.lambdaQuery(UserInfo.class).eq(UserInfo::getIndustry, industry)
                .between(StrUtil.isAllNotEmpty(startTime, endTime), UserInfo::getCreated, startTime, endTime));
        return count;
    }


    @Override
    public Integer selectAgeCount(int age1, int age2, String startTime, String endTime) {
        return userInfoMapper.selectCount(Wrappers.lambdaQuery(UserInfo.class)
                .between(UserInfo::getAge, age1, age2)
                .between(StrUtil.isAllNotEmpty(startTime, endTime), UserInfo::getCreated, startTime, endTime));
    }

    @Override
    public Integer selectSexCount(int i, String startTime, String endTime) {
        return userInfoMapper.selectCount(Wrappers.lambdaQuery(UserInfo.class)
                .eq(UserInfo::getSex, i)
                .between(StrUtil.isAllNotEmpty(startTime, endTime), UserInfo::getCreated, startTime, endTime));
    }

    @Override
    public Integer selectRegionCount(String region) {
        return userInfoMapper.selectCount(Wrappers.lambdaQuery(UserInfo.class).like(UserInfo::getCity, region));
    }


    @Override
    public Page<UserInfo> queryUserInfosByPage(Integer page, Integer pagesize, Long userId, String nickname, String city) {
        //模糊分页查询
        Page<UserInfo> userInfoPage = userInfoMapper.selectPage(new Page<>(page, pagesize), Wrappers.lambdaQuery(UserInfo.class)
                .eq(ObjectUtil.isNotNull(userId), UserInfo::getUserId, userId)
                .like(ObjectUtil.isNotNull(nickname), UserInfo::getNickName, nickname)
                .like(ObjectUtil.isNotNull(city), UserInfo::getNickName, nickname));

        return userInfoPage;
    }

    @Override
    public List<UserInfo> queryPublishInfos(List<Long> userId) {
        if (CollUtil.isEmpty(userId)) {
            return null;
        }
        return userInfoMapper.selectList(Wrappers.lambdaQuery(UserInfo.class).in(UserInfo::getUserId, userId));
    }

    @Override
    public List<LinearVo> findListGroupByIndustry(List<Long> ids) {
        List<LinearVo> vo = new ArrayList<>();
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("industry title, count(industry) amount")
                .in("user_id", ids)
                .groupBy("industry")
                .last("Order By amount DESC");
        List<Map<String, Object>> maps = userInfoMapper.selectMaps(queryWrapper);
        maps.forEach(map -> {
            LinearVo linearVo = new LinearVo();
            linearVo.setTitle(Convert.toStr(map.get("title")));
            linearVo.setAmount(Convert.toInt(map.get("amount")));
            vo.add(linearVo);
        });
        return vo;
    }

    @Override
    public List<LinearVo> findListGroupByGender(List<Long> ids) {
        List<LinearVo> vo = new ArrayList<>();
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("sex title, count(sex) amount")
                .in("user_id", ids)
                .groupBy("sex");
        List<Map<String, Object>> maps = userInfoMapper.selectMaps(queryWrapper);
        maps.forEach(map -> {
            LinearVo linearVo = new LinearVo();
            linearVo.setTitle(Convert.toInt(map.get("title")) == 1 ? "男性用户" : "女性用户");
            linearVo.setAmount(Convert.toInt(map.get("amount")));
            vo.add(linearVo);
        });
        return vo;
    }

    @Override
    public List<LinearVo> findListGroupByAge(List<Long> ids) {
        List<LinearVo> vo = new ArrayList<>();
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("age title, count(age) amount")
                .in("user_id", ids)
                .groupBy("age");
        List<Map<String, Object>> maps = userInfoMapper.selectMaps(queryWrapper);
        maps.forEach(map -> {
            LinearVo linearVo = new LinearVo();
            linearVo.setTitle(Convert.toStr(map.get("title")));
            linearVo.setAmount(Convert.toInt(map.get("amount")));
            vo.add(linearVo);
        });
        return vo;
    }

    @Override
    public List<LinearVo> findListGroupByLocation(List<Long> ids) {
        List<LinearVo> vo = new ArrayList<>();
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("city title, count(city) amount")
                .in("user_id", ids)
                .groupBy("city");
        List<Map<String, Object>> maps = userInfoMapper.selectMaps(queryWrapper);
        maps.forEach(map -> {
            LinearVo linearVo = new LinearVo();
            linearVo.setTitle(Convert.toStr(map.get("title")));
            linearVo.setAmount(Convert.toInt(map.get("amount")));
            vo.add(linearVo);
        });
        return vo;
    }

    @Override
    public List<UserInfo> finduserinfoByuserIdExIID(List<Long> uid, Long userId) {
        return userInfoMapper.selectList(Wrappers.lambdaQuery(UserInfo.class).in(UserInfo::getUserId, uid).notIn(UserInfo::getUserId, userId));
    }

    @Override
    public List<UserInfo> selectNowDayUser(String dateTime, String endOfDay, Integer sex) {
        List<UserInfo> selectList = userInfoMapper.selectList(Wrappers.lambdaQuery(UserInfo.class)
                .eq(ObjectUtil.isNotNull(sex), UserInfo::getSex, sex)
                .between(UserInfo::getCreated, dateTime, endOfDay));
        return selectList;
    }
}
